<template>
  <div>
    <Row :gutter="4" >
<!--      <Col span="3"><Dateselect ref="eventTime" v-model="dateRange" :placeholder="param.date"></Dateselect> </Col>
      <Col span="3"><Input clearable :placeholder="param.deviceCode" v-model="queryParam.where.deviceCode"></Input> </Col>-->
      <Col span="5"><DateTimeRangeSelect ref="eventTime" v-model="dateRange" :placeholder="$t('datetime')" width="100%"></DateTimeRangeSelect></Col>
      <Col span="4"><Device5gModelSelect :cate=2 ref="device5gModelSelect" width="100px" v-model="queryParam.where.deviceId"/> </Col>


      <!--      <Col span="3"><Orgselect ref="srhOrgSelect" width="200px" v-model="queryParam.where.orgId"></Orgselect> </Col>-->
      <Col span="4"><OrganizationTree ref="srhOrgSelect" width="200px" v-model="queryParam.where.orgId" :placeholder="param.organization"></OrganizationTree> </Col>
      <Col span="4"><UserSelect ref="srhUserSelect" width="200px" v-model="queryParam.where.userId" :placeholder="param.user"></UserSelect> </Col>
      <Col span="4">
        <Select v-model="queryParam.where.alarmCate"  :placeholder="param.alarmType" clearable>
          <Option v-for="item in alarmCates" :value="item.code" :key="item.code">{{ item.desc }}</Option>
        </Select>
      </Col>

      <Col span="1"><Button type="primary" icon="ios-search" @click="getData">{{param.search}}</Button></Col>
    </Row>

    <Table border :columns="columns" :data="tableData" :loading="tableLoading">
      <template slot-scope="{ row, index }" slot="map">
        <Button :disabled="!(!!row.position)" type="default" :Title="$t('map')" icon="md-globe"
                style="margin-right: 3px" @click="openMap(row)"></Button>
      </template>
    </Table>
    <TopnavPage v-model="queryParam.page" @changePage="changePage"></TopnavPage>

    <Modal v-model="map.show" :title="map.tile" width="730px">
      <div id="alarmMap" ref="alarmMap" style="height:500px;width:700px;background-color: #FFFFFF"></div>
    </Modal>

  </div>
</template>
<script>
import DateTimeRangeSelect from "_c/topnav/DateTimeRangeSelect"
import Device5gModelSelect from "_c/topnav/Device5gModelSelect";
import TopnavPage from "_c/topnav/TopnavPage";
import OrganizationTree from "_c/topnav/OrganizationTree";
import Dateselect from "_c/topnav/date2select"
import UserSelect from "_c/topnav/UserModelSelect";
import StatisticsOnlineDetail from "@/view/Home/Moudle/statistics/StatisticsOnlineDetail";
import DeviceAlarm from "@/api/DeviceAlarm";
import EnumQuery from "@/api/EnumQuery";
import LayerVector from "ol/layer/Vector";
import SourceVector from "ol/source/Vector";
import MapInfo from "@/view/Home/map/maptools/data/MapInfo";
import {pointStyle, polygonStyle} from "@/view/Home/map/maptools/tool/style";
import {solveGps} from "@/view/Home/map/maptools/tool/GpsUtils";
import {Map, View} from "ol";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";
import {apiResult} from "@/libs/util";
export default {
  name: 'StatisticsAlarmDetail',
  components: {TopnavPage, OrganizationTree, DateTimeRangeSelect,Device5gModelSelect, UserSelect, },
  computed:{
    param(){
      return{
        date: this.$t('date'),
        deviceCode:this.$t('device_code'),
        alarmType:this.$t('alarm_type'),
        search:this.$t('search'),
        organization:this.$t('select_organization'),
        user:this.$t('select_people')
      }
    },
    columns() {
      return [
        {title: this.$t('device_code'), key: 'deviceCode', sortable: true,width: 200,align: 'center',ellipsis:true,tooltip:true,tooltipTheme:'light'},
        {title: this.$t('device_name'), key: 'deviceName', sortable: true, width: 200,ellipsis:true,tooltip:true,tooltipTheme:'light'},
        {title: this.$t('organization_name'), key: 'shortName', sortable: true, width: 200,ellipsis:true,tooltip:true,tooltipTheme:'light'},
        {title: this.$t('user_name'), key: 'userName', sortable: true, ellipsis:true,width: 175},
        {title: this.$t('time'), key: 'alarmTime', sortable: true,width: 180,align: 'center'},
        {title: this.$t('alarm_type'), key: 'alarmCateDesc', sortable: true, width: 140},
        {title: this.$t('alarm_remark'), key: 'alarmDescription', sortable: true, width: 150},
        {title: this.$t('location'), key: 'position', sortable: true, width: 230,ellipsis:true,tooltip:true,tooltipTheme:'light'},
        {title: '', key: '', sortable: true, width: 80,slot:"map"},
      ]
    }
  },
  data() {
    return {
      api: new DeviceAlarm(),
      enumQuery: new EnumQuery(),
      map:{
        tile: this.$t('alarm_details'),
        show:false,
        obj:null,
        mapInfo:null,
        customLayers:{
          layerVector: null,
          sourceVector: null,
        },
      },

      alarmCates:[],

      dateRange: [],
      queryParam: {
        page: {
          pages: 1,
          size: 15,
          total: 0,
          current: 1,
        },
        where: {
          keyword: null,
          deviceId: null,
          fromTime: null,
          toTime: null,
          userId: null,
          orgId: null,
          deviceCode: null,
          isGroupBy: false,
          alarmCate: null
        },
      },
      tableData: [],
      tableLoading: false

    }
  },
  methods: {
    changePage() {
      this.getData()
    },
    getData() {
      this.tableLoading = true;
      /** 生成查询条件 */
      if (!(this.dateRange == null || this.dateRange.length < 2 || this.dateRange[0] == "")) {
        this.queryParam.where.fromTime = this.dateRange[0];
        this.queryParam.where.toTime = this.dateRange[1];
      }
      this.api.queryPage(JSON.stringify(this.queryParam)).then(res => {
        this.tableData = null;
        this.tableLoading = false;
         apiResult(res.data,false,result=>{
           this.queryParam.page.total = result.data.total;
           this.tableData = result.data.records;
           if (!!this.tableData && this.tableData.length > 0){
             this.tableData.forEach(item=>{
               item.alarmCateDesc = this.$t('alarm_cate_' + item.alarmCate)
               //console.log(item)
             })
           }
         });
        this.tableLoading = false;
      })
    },
    initMap(row){
      if (!!this.map.mapObj){
        this.map.mapObj.setTarget(null);
        this.map.mapObj.dispose()
        this.map.mapObj = null;
        this.map.customLayers.layerVector = null;
        this.map.customLayers.sourceVector = null;
      }
      this.map.mapInfo = new MapInfo().get();
      this.map.customLayers.layerVector =  new LayerVector();
      this.map.customLayers.sourceVector =  new SourceVector();
      this.map.customLayers.layerVector.setSource(this.map.customLayers.sourceVector);
      this.map.customLayers.layerVector.setStyle(polygonStyle);
      const that = this;

      const pos1 = row.position.split(",");
      let pos = [];
      pos.push(parseFloat(pos1[0]));
      pos.push(parseFloat(pos1[1]));
      //坐标系转换
      const gpsData = solveGps(row.coordinateSystem,pos[1],pos[0]);
      if (!!gpsData){
        pos[0]=gpsData.lon;
        pos[1]=gpsData.lat;
      }
      that.map.mapObj = new Map({
        target: "alarmMap", // 指向对象
        layers: [
          new TileLayer({
            source: new XYZ({
              //url: "http://webrd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}"
              url: that.map.mapInfo.sub.url[0]
            }),
          })
        ],
        loadTilesWhileAnimating: true,//支持动画
        view: new View({
          projection: this.map.mapInfo.projection, //"EPSG:4326",
          center: pos,
          zoom: 16,
        })
      });

      that.map.mapObj.addLayer(that.map.customLayers.layerVector);

      const point = new Feature({
        geometry: new Point(pos),
      });

      point.setStyle(pointStyle({online:"1",title:row.deviceName}));
      this.map.customLayers.sourceVector.addFeature(point);
    },

    openMap(row) {
      this.map.show = true;
      if (this.map.show) {
        this.$nextTick(() => {
          this.initMap(row);
        })
      }
    },
  },
  mounted() {
    /** 为了显示用，调置默认值 */
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
    start.setHours(0);
    start.setMinutes(0);
    start.setSeconds(0);
    start.setMilliseconds(0);
    end.setHours(23);
    end.setMinutes(59);
    end.setSeconds(59);
    end.setMilliseconds(999);
    this.dateRange = [start, end];
    /** 查询上下线事件 */
    this.enumQuery.get("DeviceAlarmCate").then(res => {
      apiResult(res.data,false,result=>{
        this.alarmCates=[];
        if (!!res.data.data && res.data.data.length>0){
          res.data.data.forEach(item=>{
            this.alarmCates.push(
              {
                code:item.code,
                desc:this.$t('alaram_cate_' + item.code)
              }
            )
          })
        }
      })
    })

    this.getData();
  }
}
</script>

